package edu.zut.main.thread;

public class ThreadCommunication {


    public static void main(String[] args) {
        StoreHouse storeHouse = new StoreHouse();

        //生产者
        new Thread(() -> {
            for (int i = 0; i < 20 ; i++) {
                char c = (char)(Math.random() * 26 + 'a');
                storeHouse.push(c);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者").start();

        //消费者
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                storeHouse.pop();
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者").start();
    }
}

//仓库
class StoreHouse{

    //初始化仓库的大小
    private char[] data = new char[5];
    //表示存取的数据是在哪一个位置上
    private int point = 0;

    //存
    public synchronized void push(char c){
        //仓库存满了,让生产转为等待
        while (point == data.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //不管库存满不满，都告知消费者来消费
        this.notify();
        data[point] = c;
        System.out.println("生产了："+data[point]);
        point++;
    }

    //取
    public synchronized void pop(){
        //如果库存为0，消费者转为等待
        while (point == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        point --;
        System.out.println("消费了：" + data[point]);
    }

}


